package cn.lingyangwl.framework.log.integration.hutoolhttp;

import cn.hutool.http.HttpBase;
import cn.hutool.http.HttpInterceptor;
import cn.lingyangwl.framework.core.utils.IpUtils;
import cn.lingyangwl.framework.core.utils.servlet.ServletUtils;
import cn.lingyangwl.framework.core.utils.spring.SpringUtils;
import cn.lingyangwl.framework.log.common.LogCons;
import cn.lingyangwl.framework.log.core.filter.CustomTraceUser;
import cn.lingyangwl.framework.log.utils.BraveTracerUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author shenguangyang
 */
@SuppressWarnings(value = {"rawtypes"})
@Slf4j
public class LyLogHutoolHttpInterceptor implements HttpInterceptor {

    @Override
    public void process(HttpBase httpBase) {

        String traceId = BraveTracerUtils.getTraceString();
        AtomicReference<String> loginId = new AtomicReference<>();
        Optional<HttpServletRequest> request = ServletUtils.getRequest();
        request.ifPresent(e -> loginId.set(e.getHeader(LogCons.LOGIN_ID)));

        if (StringUtils.isNotBlank(traceId)) {
            CustomTraceUser traceUser = SpringUtils.getBean(CustomTraceUser.class);
            String appName = SpringUtils.getProperty("spring.application.name");
            BraveTracerUtils.addTraceId(httpBase::header);

            httpBase.header(LogCons.TRACE_ID_HEADER, traceId);
            httpBase.header(LogCons.PRE_APP_KEY, appName);
            httpBase.header(LogCons.PRE_APP_HOST_NAME, IpUtils.getHostName());
            httpBase.header(LogCons.PRE_APP_IP, IpUtils.getHostIp());
            httpBase.header(LogCons.LOGIN_ID, StringUtils.defaultString(loginId.get(), traceUser.getLoginId()));
        } else {
            log.debug("本地threadLocal变量没有正确传递traceId,本次调用不传递traceId");
        }
    }
}
